package com.kkd.kkdapp.activity;

import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.kkd.kkdapp.Environment;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.CurrentTenderSuccessEntity;
import com.kkd.kkdapp.http.entity.EveryDayData;
import com.kkd.kkdapp.http.entity.EveryDayData1;
import com.kkd.kkdapp.http.entity.EveryDayYuebao;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.utils.AppUtil;
import com.kkd.kkdapp.utils.AuthenticationUtils;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;
import com.kkd.kkdapp.view.EditText.FinanceEditText;
import com.kkd.kkdapp.view.EditText.FinanceEditText.onFinanceEditListener;

public class CurrentTenderActivity extends BaseActivity implements
		OnClickListener {

	private final int BALANCE_CODE_ZREO = 1;
	private Context mContext = this;
	private RelativeLayout affirm_title_img;
	private TextView title_currentTender;
	private TextView canBuy_currentTender;
	private TextView rate_currentTender;
	private TextView beginTender_currentTender;
	private FinanceEditText evinvest_ed_currentTender;
	private TextView predictdayearnings_tv_currentTender;
	private TextView balance_currentTender;
	private Button next_bt_currentTender;
	private TextView rechargeofcurrent;

	private static final int DECIMAL_DIGITS = 2; // 输入框小数的位数
	private boolean FALG = false;
	private boolean SUBMITFLAG = true;
	DecimalFormat df = new DecimalFormat("0.01");
	DecimalFormat df1 = new DecimalFormat("###,##0.01");
	DecimalFormat df2 = new DecimalFormat("0.01");
	private Dialog nsfDialog; // 账户余额不足对话框
	private Dialog dialog;
	private boolean distinguish;
	private Dialog mDialog;

	private String title; // 标题
	private String surplus; // 剩余金额
	private String yuebaoid;
	private long lowestAmount;
	private String interests;
	private double rates;
	private double balance;// 账户余额

	private String bmouts;
	private String yuebaoDesc;

	private TextView tv_xiantou;
	private TextView tv_hint;
	private String yuebaoLimit;
	private double limit = 1000000;
	private Button whole_cast_bt; // 全投
	private boolean isHaveXieyi = true;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case BALANCE_CODE_ZREO:
				tv_hint.setText(yuebaoDesc);
				balance_currentTender.setText(bmouts + "");
				tv_xiantou.setText(yuebaoLimit + "元");
				if (limit >= balance) {
					limit = balance;
				}
				evinvest_ed_currentTender.setLimitMax(limit);
				break;
			}
		};
	};
	private View rel_selectXieyi;
	private ImageView iv_selectXieyi;
	private TextView tv_xieyi_everyday;
	private String url_xieYi = "";
	private String title_xieYi;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_current_tender1);
		initView();
		setListener();
	}

	@Override
	protected void onResume() {
		super.onResume();
		getAccountInfo();
		getMessage();
		initData();
	}

	private void initData() {
		// 设置天天赚标题
		if (!TextUtils.isEmpty(title)) {
			title_currentTender.setText(title);
		} else {
			title_currentTender.setText("天天赚");
		}
		// 设置可购金额
		canBuy_currentTender.setText(surplus);
		// 设置起投金额
		// beginTender_currentTender.setText(lowestAmount / 100 + "元");
		// 设置年利率
		rate_currentTender.setText(interests + "%");
		// 设置输入框提示
		evinvest_ed_currentTender.setHint("最少" + lowestAmount / 100 + "元");
		// 输入框
		try {
			if (surplus.contains(",")) {
				limit = Double.parseDouble(surplus.replaceAll(",", ""));
			} else {
				limit = Double.parseDouble(surplus);
			}
		} catch (Exception e) {
			// 忽略
		}
		evinvest_ed_currentTender.setLimitMax(limit);
		evinvest_ed_currentTender.setDecimalDigits(DECIMAL_DIGITS);
		evinvest_ed_currentTender
				.setFinanceEditListener(new onFinanceEditListener() {

					@Override
					public void onValueChanged(double toValue, double fromValue) {
						if (toValue >= 50) {
							if (isHaveXieyi) {
								next_bt_currentTender.setEnabled(true);
							} else {
								next_bt_currentTender.setEnabled(false);
							}
							FALG = true;
						} else {
							next_bt_currentTender.setEnabled(false);
							FALG = false;
						}
					}

					@Override
					public void onOutLimit() {

					}

					@Override
					public void afterValueChanged(double toValue) {
						if (toValue > 0) {
							String ratess = df
									.format((int) ((toValue * rates) * 100) * 0.01);
							predictdayearnings_tv_currentTender.setText(ratess);
						} else {
							predictdayearnings_tv_currentTender.setText("0.00");
						}
					}
				});
		evinvest_ed_currentTender
				.setOnEditorActionListener(new OnEditorActionListener() {

					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						if (actionId == EditorInfo.IME_ACTION_DONE) {
							SystemUtils.hideKeyBoard(CurrentTenderActivity.this);
							if (SUBMITFLAG) {
								SUBMITFLAG = false;
								mHandler.postDelayed(new Runnable() {

									@Override
									public void run() {
										SUBMITFLAG = true;
									}
								}, 2000);
								if (FALG) {
									if (Double
											.parseDouble(evinvest_ed_currentTender
													.getText().toString()) <= balance) {
										if (Double
												.parseDouble(evinvest_ed_currentTender
														.getText().toString()) >= 50) {
											requestEveryDayTender();
										} else {
											showToast(R.string.astrict);
										}
									} else {
										showNotSufficientFundsDialog();
									}
								}
							}
							return true;
						}
						return false;
					}
				});
		evinvest_ed_currentTender.setSelection(evinvest_ed_currentTender
				.getText().toString().length());
	}

	private void getMessage() {
		Intent intent = getIntent();
		title = intent.getStringExtra("title");
		surplus = intent.getStringExtra("surplus");
		yuebaoid = intent.getStringExtra("yuebaoid");
		lowestAmount = intent.getLongExtra("lowestAmount", 0);
		interests = intent.getStringExtra("interests");
		// rates = intent.getDoubleExtra("rates", 0);
		rates = (Double.parseDouble(interests) * 100) / (double) 365 * 0.0001;
		url_xieYi = intent.getStringExtra("url_xieYi");
		title_xieYi = intent.getStringExtra("title_xieYi");
		if (!TextUtils.isEmpty(title_xieYi)) {
			tv_xieyi_everyday.setText(title_xieYi);
		}
	}

	private void initView() {
		// 返回键
		affirm_title_img = (RelativeLayout) findViewById(R.id.affirm_title_img_currentTender);
		// 天天赚title
		title_currentTender = (TextView) findViewById(R.id.title_currentTender);
		// 可购金额
		canBuy_currentTender = (TextView) findViewById(R.id.canBuy_currentTender);
		// 利率
		rate_currentTender = (TextView) findViewById(R.id.rate_currentTender);
		// 起投金额
		beginTender_currentTender = (TextView) findViewById(R.id.beginTender_currentTender);
		// 输入框
		evinvest_ed_currentTender = (FinanceEditText) findViewById(R.id.evinvest_ed_currentTender);
		// 预计日收益
		predictdayearnings_tv_currentTender = (TextView) findViewById(R.id.predictdayearnings_tv_currentTender);
		// 余额
		balance_currentTender = (TextView) findViewById(R.id.balance_currentTender);
		// 认购
		next_bt_currentTender = (Button) findViewById(R.id.next_bt_currentTender);
		// 充值
		rechargeofcurrent = (TextView) findViewById(R.id.rechargeofcurrent);
		// 限投金额
		tv_xiantou = (TextView) findViewById(R.id.tv_xiantou);
		// 认购文字说明
		tv_hint = (TextView) findViewById(R.id.tv_hint);
		// 全投
		whole_cast_bt = (Button) this.findViewById(R.id.whole_cast_bt);
		// 是否勾选协议
		rel_selectXieyi = findViewById(R.id.rel_selectXieyi);
		iv_selectXieyi = (ImageView) findViewById(R.id.iv_selectXieyi);
		// 跳转到用户协议页面
		tv_xieyi_everyday = (TextView) findViewById(R.id.tv_xieyi_everyday);
	}

	private void setListener() {
		affirm_title_img.setOnClickListener(this);
		next_bt_currentTender.setOnClickListener(this);
		rechargeofcurrent.setOnClickListener(this);
		whole_cast_bt.setOnClickListener(this);
		rel_selectXieyi.setOnClickListener(this);
		tv_xieyi_everyday.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.affirm_title_img_currentTender:
			SystemUtils.onEvent("Current_BuyPage_Back", 1);
			finish();
			break;

		case R.id.tv_xieyi_everyday: // 跳转到用户协议
			Intent intent_xieyi = new Intent(mContext, KKDWebActivity.class);
			intent_xieyi.putExtra("url", Environment.getH5Url()
					+ "daysProtocol.html?isPost=true");
			startActivity(intent_xieyi);
			break;

		case R.id.rel_selectXieyi: // 勾选协议
			isHaveXieyi = !isHaveXieyi;
			if (isHaveXieyi) {
				iv_selectXieyi.setImageResource(R.drawable.icon_havexieyi);
				if (FALG) {
					next_bt_currentTender.setEnabled(true);
				} else {
					next_bt_currentTender.setEnabled(false);
				}
			} else {
				iv_selectXieyi.setImageResource(R.drawable.icon_noxieyi);
				next_bt_currentTender.setEnabled(false);
			}
			break;

		case R.id.rechargeofcurrent:
			SystemUtils.onEvent("Current_BuyPage_Recharge", 1);
			Intent intent = null;
			if (AppUtil.isConnect(this)) {
				if (PreferenceUtils.getInstance().getAutonym(this) == 1) {
					if (PreferenceUtils.getInstance().getBoundBankCard(this) == 1) {
						intent = new Intent(this, RechargeActivity.class);
						startActivity(intent);
					} else {
						intent = new Intent(this, ForTenderActivity.class);
						intent.putExtra("enterTypeFlag", 0);
						startActivity(intent);
					}
				} else {
					intent = new Intent(this, ForTenderActivity.class);
					intent.putExtra("enterTypeFlag", 4);
					startActivity(intent);
				}
			} else {
				showToast(R.string.network_anomaly);
			}
			break;

		case R.id.next_bt_currentTender:
			SystemUtils.onEvent("Current_BuyPage_TransferIN", 1);
			if (SUBMITFLAG) {
				SUBMITFLAG = false;
				mHandler.postDelayed(new Runnable() {

					@Override
					public void run() {
						SUBMITFLAG = true;
					}
				}, 0);
				if (FALG) {
					if (Double.parseDouble(evinvest_ed_currentTender.getText()
							.toString()) <= balance) {
						if (Double.parseDouble(evinvest_ed_currentTender
								.getText().toString()) >= 50) {
							requestEveryDayTender();
						} else {
							showToast(R.string.astrict);
						}
					} else {
						if (nsfDialog != null) {
							nsfDialog.cancel();
							nsfDialog = null;
						}
						nsfDialog = DialogUtils.notSufficientFundsDialog(this,
								new OnClickListener() {

									@Override
									public void onClick(View v) {
										switch (v.getId()) {
										case R.id.cancel_tv: // 取消
											nsfDialog.dismiss();
											break;
										case R.id.recharge_tv: // 充值

											SystemUtils
													.onEvent(
															"Current_BuyPage_Windows_Recharge",
															1);
											AuthenticationUtils
													.getAuthenticationResult(
															CurrentTenderActivity.this,
															3,
															RechargeActivity.class);
											nsfDialog.dismiss();
											break;
										}

									}
								}, false);
						nsfDialog.show();
					}
				}
			}
			break;
		case R.id.whole_cast_bt:
			if (balance != 0) {
				if (limit >= balance) {
					if (balance > lowestAmount / 100) {
						evinvest_ed_currentTender.setText(df.format(balance));
						evinvest_ed_currentTender
								.setSelection(evinvest_ed_currentTender
										.getText().toString().length());
					} else {
						showNotSufficientFundsDialog();
					}
				} else {
					if (limit > lowestAmount / 100) {
						evinvest_ed_currentTender.setText(df.format(limit));
						evinvest_ed_currentTender
								.setSelection(evinvest_ed_currentTender
										.getText().toString().length());
					} else {
						showNotSufficientFundsDialog();
					}
				}
			}
			break;

		default:
			break;
		}
	}

	/**
	 * 天天赚认购
	 */
	public void requestEveryDayTender() {
		next_bt_currentTender.setEnabled(false);
		FALG = false;
		dialog = DialogUtils.tendertoLoadDialog(
				this,
				"转入金额 "
						+ (df.format(Double
								.parseDouble(evinvest_ed_currentTender
										.getText().toString()))) + "元",
				"正在转入,请稍候...");
		dialog.show();

		KkdHttpMagager.getInstance().getEveryDayTenderManager(
				yuebaoid,
				(long) (Double.parseDouble(evinvest_ed_currentTender.getText()
						.toString()) * 100), new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						String product = "";
						next_bt_currentTender.setEnabled(true);
						FALG = true;
						dialog.dismiss();
						CurrentTenderSuccessEntity dataCurrentTenderSuccessEntity = (CurrentTenderSuccessEntity) responseBody;
						if (!"".equals(title)) {
							product = title;
						} else {
							product = "天天赚";
						}
						distinguish = true;
						showDialog(CurrentTenderActivity.this, product, df
								.format(Double
										.parseDouble(evinvest_ed_currentTender
												.getText().toString())),
								predictdayearnings_tv_currentTender.getText()
										.toString(),
								dataCurrentTenderSuccessEntity
										.getStartInterest(),
								dataCurrentTenderSuccessEntity.getIncomeTime());
					}

					@Override
					public void onFailure(int statusCode, String desc) {
						String product = "";
						next_bt_currentTender.setEnabled(true);
						FALG = true;
						dialog.dismiss();
						if (!"".equals(title)) {
							product = title;
						} else {
							product = "天天赚";
						}
						distinguish = false;
						showTenderBeDefeatedResult(desc);
						// showDialog(R.drawable.tenderresult_succeed_bedefeated,
						// desc, product, df1.format(Double
						// .parseDouble(evinvest_ed_currentTender
						// .getText().toString())),
						// "重新认购", true);
					}
				});
	}

	/**
	 * 
	 * 查询账户余额
	 */
	public void getAccountInfo() {
		KkdHttpMagager.getInstance().getAccountInfoManager(String.class,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						String responseString = responseBody.toString();
						try {
							JSONObject data = new JSONObject(responseString);
							DecimalFormat df = new DecimalFormat("0.00");
							balance = data.getDouble("balance");
							bmouts = df.format(balance);
							yuebaoDesc = data.getString("yuebaoDesc");
							yuebaoLimit = data.getString("yuebaoLimit");
							mHandler.sendEmptyMessage(BALANCE_CODE_ZREO);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, String desc) {

					}
				});
	}

	/****************** 认购结果 ******************/

	protected void showDialog(Context context, String product, String amount,
			String rishouyi, String beginJiXi, String time2shouyi) {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.subscriptionResultsDialog2(
				CurrentTenderActivity.this, product, amount, rishouyi,
				beginJiXi, time2shouyi, new OnClickListener() {

					@Override
					public void onClick(View view) {
						switch (view.getId()) {
						case R.id.finish_currenttender_result:
							SystemUtils.onEvent("Current_Result_Back", 1);
							if (mDialog != null) {
								mDialog.dismiss();
							}
							if (distinguish) {
								finish();
							}
							break;

						case R.id.textView_seeMyCurrent_currenttender_result:
							SystemUtils.onEvent("Current_Result_CheckRecord", 1);
							Intent intent = new Intent(
									CurrentTenderActivity.this,
									AccountEverydayActivity.class);
							startActivity(intent);
							if (mDialog != null) {
								mDialog.dismiss();
							}
							if (distinguish) {
								finish();
							}
							break;
						case R.id.examine:
							getAccountInfo();
							evinvest_ed_currentTender.setText("");
//							requestYuebao();
							mDialog.dismiss();
							break;
						default:
							break;
						}
					}
				});
		mDialog.show();
	}

	protected void showDialog(int imgID, String promp, String product,
			String amount, String bt_tv, boolean viewflag) {
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		mDialog = DialogUtils.subscriptionResultsDialog(
				CurrentTenderActivity.this, imgID, promp, product, amount,
				bt_tv, viewflag, new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.return_bt:
							mDialog.dismiss();
							if (distinguish) {
								finish();
							}
							break;
						case R.id.result_title_img:
							mDialog.dismiss();
							if (distinguish) {
								finish();
							}
							break;
						}
					}
				});
		mDialog.show();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mDialog != null) {
			mDialog.cancel();
			mDialog = null;
		}
		/****** 账户余额不足对话框 ************/
		if (nsfDialog != null) {
			nsfDialog.cancel();
			nsfDialog = null;
		}
		if (dialog != null) {
			dialog.cancel();
			dialog = null;
		}
	}

	/********** 认购失败结果 ************/
	public void showTenderBeDefeatedResult(String desc) {
		DialogUtils.tenderBeDefeatedResult(this, desc);
	}

	/**
	 * 天天赚详情
	 */
	private void requestYuebao() {
//		KkdHttpMagager.getInstance().getEveryDayManager(EveryDayData.class,
//				new HttpCallBack() {
//
//					@Override
//					public void onSuccess(int statusCode, Object responseBody) {
//						EveryDayData data = (EveryDayData) responseBody;
//						EveryDayData1 data1 = data.getData();
//						EveryDayYuebao yuebao = data.getYuebao();
//						long amount = yuebao.getAmount(); // 总金额
//						long buyFreeAmountSum = data1.getBuyFreeAmountSum(); // 购买金额
//						canBuy_currentTender.setText(df1
//								.format((amount - buyFreeAmountSum) * 0.01));
//					}
//
//					@Override
//					public void onFailure(int statusCode, String desc) {
//					}
//				});

	}

	/****** 账户余额不足对话框 ************/
	public void showNotSufficientFundsDialog() {
		if (nsfDialog != null) {
			nsfDialog.cancel();
			nsfDialog = null;
		}
		nsfDialog = DialogUtils.notSufficientFundsDialog(this,
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						switch (v.getId()) {
						case R.id.cancel_tv: // 取消
							nsfDialog.dismiss();
							break;
						case R.id.recharge_tv: // 充值

							SystemUtils.onEvent(
									"Regular_BidPage_Windows_Recharge", 1);
							AuthenticationUtils.getAuthenticationResult(
									CurrentTenderActivity.this, 3,
									RechargeActivity.class);
							nsfDialog.dismiss();
							break;
						}

					}
				}, false);
		nsfDialog.show();
	}
}
